<template>
  <div class="upload-image">
    <el-upload
      class="avatar-uploader"
      :class="{ disabled: value }"
      action="#"
      list-type="picture-card"
      :before-upload="beforeAvatarUpload"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :file-list="fileList"
      accept="image/png, image/jpeg, image/webp"
      :http-request="handleUpload"
    >
      <!-- 有头像显示头像，没头像显示加号 -->
      <!-- <img v-if="value" :src="value" class="avatar"> -->
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 预览弹框 -->
    <el-dialog title="预览" :visible="isShow" @close="isShow = false">
      <img :src="value">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'UploadImg',
  props: {
    // 接受父组件传的value属性(头像地址)
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isShow: false
    }
  },
  computed: {
    fileList: {
      get() {
        return this.value ? [{ url: this.value }] : []
      },
      set() {

      }
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 文件移除时的钩子
    handleRemove() {
      // 点击删除时同时删除数据(把value值清空)
      // 子传父，触发v-model的input事件，并传递空字符串
      this.$emit('input', '')
    },
    // 预览
    handlePreview() {
      this.isShow = true
    },
    // 上传
    // file：选择图片的文件对象
    handleUpload({ file }) {
      // 把选择的图片发到腾讯云服务器
      // 1.实例化COS
      const cos = new COS({
        SecretId: 'AKIDqX0GKAoFSRCbnnZ6QWP6aqsgQxKXaS9g',
        SecretKey: 'Zy96pMglevypRp22pPnxueBVfbO1RddQ'
      })
      cos.putObject({
        Bucket: 'lfy-1317090667', // 桶的名字
        Region: 'ap-beijing', // 服务器地区
        Key: file.name, // 文件名
        Body: file // 文件对象
      }, (err, data) => {
        console.log(err || data)
        if (err) {
          console.dir(err)
          return this.$message.error('上传失败')
        }
        // 拿到上传成功的图片地址，同步到父组件中
        this.$emit('input', `http://${data.Location}`)
      })
    }
  }
}
</script>

<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .disabled {
    .el-upload {
      display: none;
    }
  }
</style>
